﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Telerik.WinControls;
using VIFON.BLL;
using VIFON.DAL;

namespace VIFON
{
    public partial class frmShowBill : Telerik.WinControls.UI.RadForm
    {
        public frmShowBill()
        {
            InitializeComponent();
        }

        BLCustomer blCustomer = new BLCustomer();
        BLProduct blProduct = new BLProduct();
        BLBill blBill = new BLBill();
        BLBillDetails blBillDetails = new BLBillDetails();
        private void LoadCustomer()
        {
            ddCustomer.DisplayMember = "CustomerName";
            ddCustomer.ValueMember = "Id";
            ddCustomer.DataSource = blCustomer.GetCustomersList();            
        }
        private void frmShowBill_Load(object sender, EventArgs e)
        {
            LoadCustomer();
            radCreatedDate.Format = DateTimePickerFormat.Custom;
            radCreatedDate.CustomFormat = "MM/yyyy";
        }
        private void ShowAll()
        {
            try
            {
                using (var db = new DBVIFONDataContext())
                {
                    var Sql = from customer in db.Customers
                              from region in db.Regions
                              from payment in db.PaymentTypes
                              from product in db.Products
                              from bill in db.Bills
                              from billdetails in db.BillDetails
                              from unitype in db.UnitTypes
                              where customer.Region == region.Id
                              && customer.PaymentType == payment.Id
                              && customer.Id == bill.CustomerId
                              && billdetails.BillId == bill.Id
                              && billdetails.ProductId == product.Id
                              && customer.Id == int.Parse(ddCustomer.SelectedValue.ToString())
                              select new
                              {
                                  Discount = customer.Discount,
                                  TaxCode = customer.TaxCode,
                                  Address = customer.Address,
                                  AccNumber = customer.AccountNumber,
                                  PamentName = payment.Name,
                                  CarId = bill.CarId,
                                  Stan = bill.Stan,
                                  Notation = bill.Notation,
                                  BillId = bill.Id,
                                  BillCreatedDate = bill.CreatedDate,
                                  ProductName = product.ProductName,
                                  ProductPrice = product.Prices,
                                  UnitName = unitype.UnitName,
                                  Amounts = billdetails.Amounts,
                                  RegionName = region.Name,
                                  DiscountPrice = product.Prices - ((product.Prices*customer.Discount)/100),
                                  TotalPrice = (product.Prices - ((product.Prices * customer.Discount) / 100)) * billdetails.Amounts,                                 
                              };
                    grvshowbill.DataSource = Sql.ToList();                       
                    var SumAmounts = Sql.Select(temp => temp.Amounts).Sum();
                    var Totals = Sql.Select(sumtotal => sumtotal.TotalPrice).Sum();    
                    var Totals2 = Totals - int.Parse(txtdiscountprice.Text);
                    //if(!String.IsNullOrEmpty(Sql.Select(temp=>temp.Package).ToString()))
                    //{
                    //    var Totalpackage = Sql.Select(pack => pack.Package).Sum();
                    //    lbltotalpackage.Text = Totalpackage.ToString() + "bao";
                    //}
                    //else
                    //{
                    //    lbltotalpackage.Text = "";
                    //}
                    
                    lbltotalweight.Text = SumAmounts.ToString() +" kg";
                    //lblsumtotal.Text = Totals.ToString();
                    lblsumtotal.Text = String.Format("{0:0,0}", Totals).Replace(",", ".") + ",00";
                    lbltotal.Text = String.Format("{0:0,0}", Totals2).Replace(",", ".") + ",00";                    
                    var VAT = Totals2 / int.Parse(txtvat.Text);
                    lblGTGT.Text = String.Format("{0:0,0}", VAT).Replace(",", ".") + ",00"; ;
                    var SumAll = Totals2 + VAT;
                    lblTotalSum.Text = String.Format("{0:0,0}", SumAll).Replace(",", ".") + ",00";
                    lblmoneybychar.Text = DocSoThanhChu(SumAll.ToString()) + " đồng chẳn";
                    foreach (var item in Sql)
                    {
                        //Area information for Customer
                        lbltaxcode.Text = item.TaxCode;
                        lbladdress.Text = item.Address;
                        lblPaymentType.Text = item.PamentName;
                        lblAccount.Text = item.AccNumber;
                        lblCarId.Text = item.CarId;
                        //Area information for Bill
                        lblStan.Text = item.Stan;
                        lblNotation.Text = item.Notation;
                        lblbillId.Text = item.BillId.ToString();
                        lblCreatedDate.Text = item.BillCreatedDate;                        
                        //grvshowbill.Rows.Add("",item.ProductName, item.UnitName, item.Amounts, item.DiscountPrice, item.TotalPrice);
                    }
                    for(int i=0;i<grvshowbill.Rows.Count;i++)
                    {
                        grvshowbill.Rows[i].Cells[0].Value = i + 1;                        
                    }

                }
            }
            catch (Exception ex) { }
        }

        private void ddCustomer_SelectedIndexChanged(object sender, Telerik.WinControls.UI.Data.PositionChangedEventArgs e)
        {
            ShowAll();
        }

        private void txtdiscountprice_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (!Char.IsDigit(e.KeyChar) && !Char.IsControl(e.KeyChar))
                e.Handled = true;
        }

        private void txtdiscountprice_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                ShowAll();
            }
        }
        private string DocSoThanhChu(string number)//<=
        {
            string strReturn = "";
            string s = number;
            while (s.Length > 0 && s.Substring(0, 1) == "0")
            {
                s = s.Substring(1);
            }
            string[] so = new string[] { "không", "một", "hai", "ba", "bốn", "năm", "sáu", "bảy", "tám", "chín" };
            string[] hang = new string[] { "", "nghìn", "triệu", "tỷ" };
            int i, j, donvi, chuc, tram;

            bool booAm = false;
            decimal decS = 0;

            try
            {
                decS = Convert.ToInt64(s.ToString());
            }
            catch { }

            if (decS < 0)
            {
                decS = -decS;
                //s = decS.ToString();
                booAm = true;
            }
            i = s.Length;
            if (i == 0)
                strReturn = so[0] + strReturn;
            else
            {
                j = 0;
                while (i > 0)
                {
                    donvi = Convert.ToInt32(s.Substring(i - 1, 1));
                    i--;
                    if (i > 0)
                        chuc = Convert.ToInt32(s.Substring(i - 1, 1));
                    else
                        chuc = -1;
                    i--;
                    if (i > 0)
                        tram = Convert.ToInt32(s.Substring(i - 1, 1));
                    else
                        tram = -1;
                    i--;
                    if ((donvi > 0) || (chuc > 0) || (tram > 0) || (j == 3))
                        strReturn = hang[j] + strReturn;
                    j++;
                    if (j > 3) j = 1;   //Tránh lỗi, nếu dưới 13 số thì không có vấn đề.
                    //Hàm này chỉ dùng để đọc đến 9 số nên không phải bận tâm
                    if ((donvi == 1) && (chuc > 1))
                        strReturn = "mốt " + strReturn;
                    else
                    {
                        if ((donvi == 5) && (chuc > 0))
                            strReturn = "năm " + strReturn;
                        else if (donvi > 0)
                            strReturn = so[donvi] + " " + strReturn;
                    }
                    if (chuc < 0) break;//Hết số
                    else
                    {
                        if ((chuc == 0) && (donvi > 0)) strReturn = "lẻ " + strReturn;
                        if (chuc == 1) strReturn = "mười " + strReturn;
                        if (chuc > 1) strReturn = so[chuc] + " mươi " + strReturn;
                    }
                    if (tram < 0) break;//Hết số
                    else
                    {
                        if ((tram > 0) || (chuc > 0) || (donvi > 0)) strReturn = so[tram] + " trăm " + strReturn;
                    }
                    strReturn = " " + strReturn;
                }
            }
            if (booAm) strReturn = "Âm " + strReturn;
            return strReturn.Trim();// = str+ "đồng chẵn";
        }

    }
}
